'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 离开战斗
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var _ = require('lodash');
var Code = require('../../../consts/code');
var constantUtil = require('../../../util/constantUtil');
var roleService = require('../../../services/roleService');
var PlayerManager = require('../../../libs/playerManager');
var taskService = require('../../../services/taskService');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * 离开副本
 * 需要上传的数据:
 * 1.已经拆除的建筑
 * 2.已经打过的经济类的建筑
 * 3.要统计的数据
 */
Handler.prototype.exit = function (msg, session, next) {
    var role_id = session.uid;

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['survive', 'task', 'daily_task', 'achieve', 'sevenDayActivity', 'accrued'],
                    cb);
            },
            function (cb) {
                var survive_model = player_manager.survive;
                taskService.addInSurvival(player_manager);
                survive_model.setEnd();
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK
            });
        }
    );
};
